#!/usr/bin/env python
"""
GitCode MCP客户端测试脚本
"""
import asyncio
import json
import os
from mcp.client.client import MCPClient

async def test_mcp_client():
    """测试MCP客户端连接和API调用"""
    print("正在连接GitCode MCP服务器...")
    
    # 创建客户端实例
    client = MCPClient()
    
    # 启动服务器进程并连接
    process = await client.start_stdio_server(
        command=["python", "-m", "gitcode_mcp.server"],
        env={"GITCODE_TOKEN": os.environ.get("GITCODE_TOKEN", "")}
    )
    
    print("成功连接到服务器！")
    
    try:
        # 列出可用工具
        print("\n===== 可用工具 =====")
        tools = await client.list_tools()
        for tool in tools:
            print(f"- {tool.name}: {tool.description}")
        
        # 如果已配置GitCode令牌，测试列出仓库
        if os.environ.get("GITCODE_TOKEN"):
            print("\n===== 列出仓库 =====")
            try:
                result = await client.call_tool("list_repositories")
                repos = json.loads(result.value)
                print(f"找到 {len(repos)} 个仓库:")
                for repo in repos[:5]:  # 只显示前5个
                    print(f"  - {repo.get('full_name', 'unknown')}: {repo.get('description', '')}")
                if len(repos) > 5:
                    print(f"  ... 及其他 {len(repos)-5} 个仓库")
            except Exception as e:
                print(f"调用失败: {e}")
        else:
            print("\n⚠️ 未配置GITCODE_TOKEN环境变量，跳过API测试")
        
        # 列出可用资源
        print("\n===== 可用资源 =====")
        resources = await client.list_resources()
        for resource in resources:
            print(f"- {resource.uri}: {resource.description}")
            
        # 列出可用提示
        print("\n===== 可用提示 =====")
        prompts = await client.list_prompts()
        for prompt in prompts:
            print(f"- {prompt.name}: {prompt.description}")
            
    finally:
        # 清理
        print("\n正在关闭连接...")
        await client.close()
        if process and process.returncode is None:
            process.terminate()
            await process.wait()
        print("测试完成！")

if __name__ == "__main__":
    asyncio.run(test_mcp_client()) 